import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

import {Observable} from 'rxjs';
import {catchError} from 'rxjs/operators';
import {getToken} from '../../util/token.util';

/**
 * 在每次发送 http 请求的时候在 head 上加上登陆验证信息（如果当前已登陆）
 */
@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  AUTHORIZATION_HTTP_HEAD_KEY = 'Authorization';

  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = getToken();
    if (token != null) {
      const secureReq = request.clone({
        headers: request.headers.set(this.AUTHORIZATION_HTTP_HEAD_KEY, token)
      });
      return next.handle(secureReq).pipe(catchError(this.handleError));
    } else {
      return next.handle(request);
    }
  }

  private handleError(error: HttpErrorResponse): never {
    throw error.error;
  }
}
